const finance = require('../../../utils/finance')
const { formatyyyyMMdd, formatDateTimeNoSeconds} = require('../../../utils/date');
const app = getApp();

Page({
    data: {
      type: 'expense',
      amount: '',
      financeTime: '', // 新增记账时间字段
      // 系统支出分类列表
      expenseCategoryList: [
        // { name: '餐饮', icon: '/assets/finance/finance-sys-catering.svg' },
        // { name: '交通', icon: '/assets/finance/finance-sys-traffic.svg' },
        // { name: '购物', icon: '/assets/finance/finance-sys-shop.svg' },
        // { name: '居住', icon: '/assets/finance/finance-sys-house.svg' },
        // { name: '通讯', icon: '/assets/finance/finance-sys-network.svg' },
        // { name: '服饰', icon: '/assets/finance/finance-sys-cloth.svg' },
        // { name: '娱乐', icon: '/assets/finance/finance-sys-recreation.svg' },
        // { name: '教育', icon: '/assets/finance/finance-sys-study.svg' },
        // { name: '医疗', icon: '/assets/finance/finance-sys-medical.svg' },
        // { name: '人情', icon: '/assets/finance/finance-sys-social.svg' },
        // { name: '意外', icon: '/assets/finance/finance-sys-accident.svg' },
        // { name: '其他', icon: '/assets/finance/finance-sys-other.svg' }
      ],
      // 系统收入分类列表
      incomeCategoryList: [
        // { name: '工资', icon: '/assets/finance/finance-sys-salary.svg' },
        // { name: '奖金', icon: '/assets/finance/finance-sys-bonus.svg' },
        // { name: '金融', icon: '/assets/finance/finance-sys-financial.svg' },
        // { name: '兼职', icon: '/assets/finance/finance-sys-parttime.svg' },
        // { name: '生意', icon: '/assets/finance/finance-sys-business.svg' },
        // { name: '报销', icon: '/assets/finance/finance-sys-reimburse.svg' },
        // { name: '赠与', icon: '/assets/finance/finance-sys-bestow.svg' },
        // { name: '礼物', icon: '/assets/finance/finance-sys-gift.svg' },
        // { name: '退款', icon: '/assets/finance/finance-sys-refund.svg' },
        // { name: '其他', icon: '/assets/finance/finance-sys-other.svg' },
      ],
      categoryName: '',
      categoryIcon: '',
      categoryIndex: -1, // 添加分类索引初始化
      showCategoryModal: false,
      financeDate: '',
      dateList: [], // 新增
      remark: '',
      // 账户列表
      accountList: [],
      accountIndex: 0,
      // 支付方式列表
      paymentList: [{name: '支付宝', defaultFlag: 'yes'}],
      paymentIndex: 0,
      details: [],
      // 语音识别相关数据
      showVoiceModal: false,
      isRecording: false,
      recordingTime: '00:00',
      sliderValue: 0,
      sliderProgress: 0,
      recordingTimer: null,
      recordingStartTime: 0,
      recorderManager: null,
      recordId: 0,
      showAccountSelector: false, // 新增
      submitDisabled: false, // 新增
      submitBtnText: '记一笔', // 新增
      // 媒体资源相关
      resourceUrl: '', // 资源路径
      mediaType: '', // 资源类型：audio音频，image图片
      isAudioPlaying: false, // 新增：音频播放状态
      // 音频播放进度相关
      audioDuration: 0, // 音频总长度（秒）
      audioCurrentTime: 0, // 当前播放时间（秒）
      audioProgress: 0, // 播放进度百分比
    },
    async onLoad(options) {
      // 1. 优先本地缓存账户
      const { accountList, accountIndex } = await app.getAccountGlobal();
      
      // 验证账户索引是否有效
      let safeAccountIndex = accountIndex;
      if (accountList && accountList.length > 0) {
        if (accountIndex < 0 || accountIndex >= accountList.length) {
          safeAccountIndex = 0; // 如果索引无效，默认使用第一个账户
        }
      } else {
        safeAccountIndex = 0; // 如果没有账户，设置为0
      }
      
      this.setData({ accountList, accountIndex: safeAccountIndex });
      
      // 2. 继续原有初始化逻辑
      const type = options.type || 'expense';
      const recordId = options.id || '';
      const date = options.date || ''; // 新增日期参数处理
      
      // 获取初始化参数
      try {
        const res = await finance.writeInitParam();
        if (res) {
          // 分类处理
          let expenseCategoryList = [];
          let incomeCategoryList = [];
          if (Array.isArray(res.categoryList)) {
            expenseCategoryList = res.categoryList.filter(item => item.type === 'expense');
            incomeCategoryList = res.categoryList.filter(item => item.type === 'income');
          }

          const dateList = Array.isArray(res.dateList) && res.dateList.length > 0? res.dateList: [];
          const paymentList = Array.isArray(res.paymentList) && res.paymentList.length > 0 ? res.paymentList : [];
          // 查找第一个defaultFlag为yes的index
          const paymentIndex = Math.max(0, paymentList.findIndex(item => item.defaultFlag === 'yes'));
          
          // 设置日期，优先使用传入的日期参数
          let financeDate = res.dateList[dateList.length - 1];
          if (date) {
            financeDate = date;
          }
          
          this.setData({
            dateList: dateList,
            financeDate: financeDate,
            paymentList,
            paymentIndex,
            expenseCategoryList,
            incomeCategoryList
          });

          if (recordId){
            this.setData({ recordId });
            // 调用接口去查询详情数据
            try {
              const res = await finance.getFinanceRecordDetail(recordId);
              if (res) {
                // 如果有financeTime字段，保存到data中
                if (res.financeTime) {
                  this.setData({ financeTime: res.financeTime });
                }
                this.fillFormWithAnalysis(res);
              }
            } catch (e) {
              wx.showToast({ title: (e && e.data && e.data.msg) || '加载详情失败', icon: 'none' });
            }
          } else{
            // 新增需要选择分类
            this.showCategoryModal();
            this.setData({ type, recordId });
          }

        } else {
          // 如果没有初始化参数，使用传入的日期或当前日期
          const defaultDate = date || formatyyyyMMdd(new Date());
          this.setData({ financeDate: defaultDate, dateList: [] });
        }
      } catch (e) {
        // 异常情况下，使用传入的日期或当前日期
        const defaultDate = date || formatyyyyMMdd(new Date());
        this.setData({ financeDate: defaultDate, dateList: [defaultDate] });
      }
    },
    onTabChange(e) {
      const type = e.currentTarget.dataset.type;
      this.setData({ 
        type,
        categoryIndex: -1, // 重置分类索引
        categoryName: '', // 重置分类名称
        categoryIcon: '' // 重置分类图标
      });
      this.showCategoryModal();
    },
    showCategoryModal() {
      this.setData({ showCategoryModal: true });
    },
    onCategorySelect(e) {
      const { index, type, item } = e.detail;
      // 选中后设置分类名、图标、索引，关闭弹窗
      this.setData({
        categoryName: item.name,
        categoryIcon: item.icon,
        categoryIndex: index,
        showCategoryModal: false
      });
    },
    onCategoryModalClose() {
      this.setData({ showCategoryModal: false });
    },
    onAmountInput(e) {
      this.setData({ amount: e.detail.value });
    },
    onDateChange(e) {
      if (this.data.dateList && this.data.dateList.length > 0) {
        // 多日期选择
        const idx = e.detail.value;
        this.setData({ financeDate: this.data.dateList[idx] });
      } else {
        // 普通日期选择
        this.setData({ financeDate: e.detail.value });
      }
    },
    onRemarkInput(e) {
      this.setData({ remark: e.detail.value });
    },
    /**
     * 选择账户
     * @param {*} e 
     */
    onAccountChange(e) {
      // 设置全局账户索引
      app.setAccountIdxGlobal(e.detail.value);
      this.setData({ accountIndex: e.detail.value });
    },
    onCategoryTap() {
      this.showCategoryModal();
    },
    /**
     * 
     * @returns 确定操作(新增或编辑表单)
     */
    onSubmit() {
      if (!this.data.amount || !this.data.categoryName) {
        wx.showToast({ title: '请填写金额和选择类别', icon: 'none' });
        return;
      }

       // 处理明细字段映射
       const itemList = (this.data.details || []).map(item => ({
        financeName: item.name,
        financeUnit: item.unitPrice, // unitPrice转unit
        financeQuantity: item.quantity,
        amount: item.amount,
        timeStr: item.timeStr,
      }));

      const param = {
        type: this.data.type,
        totalAmount: this.data.amount,
        categoryCode: this.data.categoryName,
        categoryName: this.data.categoryName,
        paymentMethod:  this.data.paymentList[this.data.paymentIndex].name,
        financeDate: this.data.financeDate,
        financeDesc: this.data.remark,
        // 收支类型
        financeType: this.data.type,
        // 账户id
        accountBookId: this.data.accountList[this.data.accountIndex].id,
        itemList: itemList,
        resourceUrl: this.data.resourceUrl,
        mediaType: this.data.mediaType
      };
      wx.showLoading({ title: '保存中...' });
      if (this.data.recordId) {
        // 编辑
        finance.editFinanceRecord(this.data.recordId, param).then(() => {
          wx.hideLoading();
          wx.showToast({ title: '编辑成功', icon: 'success' });
          this.backAndRefresh();
        }).catch((e) => {
          wx.hideLoading();
          wx.showToast({ title:  (e && e.data && e.data.msg) || '编辑失败', icon: 'none' });
        });
      } else {
        // 新增
        finance.saveFinanceRecord(param).then(() => {
          wx.hideLoading();
          wx.showToast({ title: '保存成功', icon: 'success' });
          this.backAndRefresh();
        }).catch((e) => {
          wx.hideLoading();
          wx.showToast({ title:  (e && e.data && e.data.msg) || '保存失败', icon: 'none' });
        });
      }
    },
    onAddDetail() {
      const details = this.data.details || [];
      details.push({
        id: Date.now(),
        name: '',
        unitPrice: '',
        quantity: 1,
        amount: ''
      });
      this.setData({ details });
    },
    onDetailNameInput(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      details[idx].name = e.detail.value;
      this.setData({ details });
    },
    onDetailUnitPriceInput(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      details[idx].unitPrice = e.detail.value;
      const qty = Number(details[idx].quantity) || 1;
      const price = Number(e.detail.value) || 0;
      details[idx].amount = (qty * price).toFixed(2);
      this.setData({ details }, () => {
        this.updateAmountFromDetails();
      });
    },
    onDetailQuantityInput(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      let qty = Number(e.detail.value) || 1;
      if (qty < 1) qty = 1;
      details[idx].quantity = qty;
      const price = Number(details[idx].unitPrice) || 0;
      details[idx].amount = (qty * price).toFixed(2);
      this.setData({ details }, () => {
        this.updateAmountFromDetails();
      });
    },
    onQtyPlus(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      let qty = Number(details[idx].quantity) || 1;
      qty++;
      details[idx].quantity = qty;
      const price = Number(details[idx].unitPrice) || 0;
      details[idx].amount = (qty * price).toFixed(2);
      this.setData({ details }, () => {
        this.updateAmountFromDetails();
      });
    },
    onQtyMinus(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      let qty = Number(details[idx].quantity) || 1;
      if (qty > 1) qty--;
      details[idx].quantity = qty;
      const price = Number(details[idx].unitPrice) || 0;
      details[idx].amount = (qty * price).toFixed(2);
      this.setData({ details }, () => {
        this.updateAmountFromDetails();
      });
    },
    onDetailAmountInput(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      details[idx].amount = e.detail.value;
      this.setData({ details }, () => {
        this.updateAmountFromDetails();
      });
    },
    onDeleteDetail(e) {
      const idx = e.currentTarget.dataset.index;
      const details = this.data.details;
      details.splice(idx, 1);
      this.setData({ details }, () => {
        this.updateAmountFromDetails();
      });
    },
    
    // 语音识别相关方法
    onVoiceInput() {
      this.checkRecordAuth();
    },
    
    // 检查录音权限
    checkRecordAuth() {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.record']) {
            wx.authorize({
              scope: 'scope.record',
              success: () => {
                this.showVoiceModal();
              },
              fail: () => {
                wx.showModal({
                  title: '需要录音权限',
                  content: '请在设置中开启录音权限',
                  showCancel: false,
                  confirmText: '去设置',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting();
                    }
                  }
                });
              }
            });
          } else {
            this.showVoiceModal();
          }
        }
      });
    },
    
    // 显示录音模态框
    showVoiceModal() {
      this.setData({
        showVoiceModal: true,
        isRecording: false,
        sliderValue: 0,
        sliderProgress: 0,
        recordingTime: '00:00'
      });
      
      // 初始化录音管理器
      if (!this.data.recorderManager) {
        const recorderManager = wx.getRecorderManager();
        recorderManager.onStart(() => {
          console.log('录音开始');
        });
        recorderManager.onStop((res) => {
          console.log('录音结束', res);
          this.handleRecordResult(res);
        });
        recorderManager.onError((res) => {
          console.error('录音错误', res);
          wx.showToast({ title: '录音失败', icon: 'none' });
          this.stopRecording();
        });
        this.setData({ recorderManager });
      }
      
      // 获取滑动容器的实际宽度
      this.getSliderContainerWidth();
    },
    
    // 获取滑动容器宽度
    getSliderContainerWidth() {
      const query = wx.createSelectorQuery();
      query.select('.voice-slider-track').boundingClientRect((rect) => {
        if (rect) {
          // 更精确的计算，考虑滑块的实际位置
          this.sliderMaxValue = rect.width - 80; // 减去滑块宽度
          this.sliderContainerWidth = rect.width;
          console.log('滑动容器宽度:', rect.width, '最大滑动距离:', this.sliderMaxValue);
        }
      }).exec();
    },
    
    // 关闭录音模态框
    onVoiceModalClose() {
      if (this.data.isRecording) {
        this.stopRecording();
      }
      this.setData({ showVoiceModal: false });
    },
    
    // 滑动开始
    onSliderTouchStart(e) {
      this.touchStartX = e.touches[0].clientX;
      this.sliderStartValue = this.data.sliderValue;
      this.isSliding = true;
      this.hasTriggeredRecording = false; // 重置触发状态
    },
    
    // 滑动中
    onSliderTouchMove(e) {
      if (!this.isSliding || this.hasTriggeredRecording) return;
      
      // 防止页面滚动
      e.preventDefault && e.preventDefault();
      
      const touchX = e.touches[0].clientX;
      const deltaX = touchX - this.touchStartX;
      let newValue = this.sliderStartValue + deltaX;
      
      // 限制滑动范围
      const maxValue = this.sliderMaxValue || 200;
      if (newValue < 0) newValue = 0;
      if (newValue > maxValue) newValue = maxValue;
      
      // 计算进度条宽度百分比
      const progress = (newValue / maxValue) * 100;
      
      // 使用节流更新UI，提高性能
      if (!this.updateTimer) {
        this.updateTimer = setTimeout(() => {
          this.setData({ 
            sliderValue: newValue,
            sliderProgress: progress
          });
          this.updateTimer = null;
        }, 16); // 约60fps
      }
      
      // 只有滑动到98%以上才触发录音，确保用户真的想录音
      if (newValue >= maxValue * 0.98 && !this.data.isRecording && !this.hasTriggeredRecording) {
        this.hasTriggeredRecording = true;
        // 确保滑块到达最右侧
        this.setData({ 
          sliderValue: maxValue,
          sliderProgress: 100
        });
        this.startRecording();
      }
    },
    
    // 滑动结束
    onSliderTouchEnd(e) {
      this.isSliding = false;
      
      // 清理更新定时器
      if (this.updateTimer) {
        clearTimeout(this.updateTimer);
        this.updateTimer = null;
      }
      
      if (!this.data.isRecording && !this.hasTriggeredRecording) {
        // 如果没有开始录音，检查是否滑动到足够距离
        const maxValue = this.sliderMaxValue || 200;
        if (this.data.sliderValue >= maxValue * 0.95) { // 滑动到95%位置才触发
          this.hasTriggeredRecording = true;
          // 确保滑块到达最右侧
          this.setData({ 
            sliderValue: maxValue,
            sliderProgress: 100
          });
          this.startRecording();
        } else {
          // 滑动距离不够，重置滑块
          this.setData({ 
            sliderValue: 0,
            sliderProgress: 0
          });
        }
      }
    },
    
    // 开始录音
    startRecording() {
      // 防止重复触发
      if (this.data.isRecording) return;
      
      this.setData({ 
        isRecording: true,
        recordingStartTime: Date.now()
      });
      
      // 开始录音
      this.data.recorderManager.start({
        duration: 60000, // 最长60秒
        sampleRate: 16000,
        numberOfChannels: 1,
        encodeBitRate: 48000,
        format: 'mp3'
      });
      
      // 开始计时
      this.startTimer();
      
      // 显示录音开始提示
      wx.showToast({ 
        title: '开始录音', 
        icon: 'success',
        duration: 1500
      });
      
      // 震动反馈（如果支持）
      if (wx.vibrateShort) {
        wx.vibrateShort();
      }
    },
    
    // 停止录音
    stopRecording() {
      if (this.data.recorderManager) {
        this.data.recorderManager.stop();
      }
      
      if (this.data.recordingTimer) {
        clearInterval(this.data.recordingTimer);
        this.setData({ recordingTimer: null });
      }
      
      this.setData({ isRecording: false });
    },
    
    // 开始计时器
    startTimer() {
      const timer = setInterval(() => {
        const elapsed = Math.floor((Date.now() - this.data.recordingStartTime) / 1000);
        const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
        const seconds = (elapsed % 60).toString().padStart(2, '0');
        this.setData({ recordingTime: `${minutes}:${seconds}` });
      }, 1000);
      
      this.setData({ recordingTimer: timer });
    },
    
    // 取消录音
    onVoiceCancel() {
      this.stopRecording();
      this.setData({ showVoiceModal: false });
    },
    
    // 结束录音并分析
    onVoiceEnd() {
      this.stopRecording();
      // 录音会在onStop回调中处理
    },
    
    // 处理录音结果
    handleRecordResult(res) {
      wx.showLoading({ title: '正在解析...' });
      
      // 将录音文件转为base64
      wx.getFileSystemManager().readFile({
        filePath: res.tempFilePath,
        encoding: 'base64',
        success: (fileRes) => {
          // 调用音频分析接口
          finance.audioRecordRecognition({
            content: fileRes.data,
            imgBase64: '', // 这里可以传入截图等
            type: this.data.type
          }).then((analysisRes) => {
            wx.hideLoading();
            this.fillFormWithAnalysis(analysisRes);
            this.setData({ showVoiceModal: false });
            wx.showToast({ title: '解析成功', icon: 'success' });
          }).catch((e) => {
            wx.hideLoading();
            console.error('音频分析失败', e);
            wx.showToast({ title:  (e && e.data && e.data.msg) || '解析失败，请重试', icon: 'none' });
          });
        },
        fail: (e) => {
          wx.hideLoading();
          console.error('读取录音文件失败', e);
          wx.showToast({ title:  (e && e.data && e.data.msg) || '录音文件读取失败', icon: 'none' });
        }
      });
    },
    // 公共图片选择和识别逻辑
    handleImageRecognition(apiFunc, loadingText, successText, failText) {
      wx.getSetting({
        success: (res) => {
          const albumAuth = res.authSetting['scope.writePhotosAlbum'] !== false;
          const cameraAuth = res.authSetting['scope.camera'] !== false;
          if (!albumAuth || !cameraAuth) {
            wx.showModal({
              title: '需要授权',
              content: '请授权相机和相册权限以便识别',
              confirmText: '去设置',
              showCancel: true,
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting();
                }
              }
            });
            return;
          }
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (chooseRes) => {
              const filePath = chooseRes.tempFilePaths[0];
              wx.getFileSystemManager().readFile({
                filePath,
                encoding: 'base64',
                success: (fileRes) => {
                  wx.showLoading({ title: loadingText });
                  apiFunc({
                    content: fileRes.data,
                    type: this.data.type
                  }).then((res) => {
                    wx.hideLoading();
                    wx.showToast({ title: successText, icon: 'success' });
                    this.fillFormWithAnalysis(res);
                  }).catch((err) => {
                    wx.hideLoading();
                  });
                },
                fail: () => {
                  wx.showToast({ title: '图片读取失败', icon: 'none' });
                }
              });
            },
            fail: () => {
              wx.showToast({ title: '未选择图片', icon: 'none' });
            }
          });
        }
      });
    },
    // 根据分析结果填充表单
    fillFormWithAnalysis(analysisRes) {
      try {
        const data = analysisRes.data || analysisRes;
        
        // 填充基本信息
        if (data.total) {
          this.setData({ amount: data.total.toString() });
        }
        
        // 处理记账时间
        if (data.financeTime) {
          this.setData({ financeTime: formatDateTimeNoSeconds(data.financeTime) });
        }

        // 账户id
        if (data.accountBookId) {
          const accountIndex = Math.max(-1, this.data.accountList.findIndex(item => item.id == data.accountBookId));
          // 账户找到在本地
          if (accountIndex >= 0) {
            // 找到账户并赋值
            this.setData({ accountIndex});
          }
        }

        // 设置媒体资源
        if (data.resourceUrl && data.mediaType){
          // 设置类型
          this.setData({ resourceUrl: data.resourceUrl, mediaType: data.mediaType});
        }

        // 记账类型
        if (data.financeType){
          // 设置类型
          this.setData({ type: data.financeType});
        }

        // 判断是否可以编辑
        if (!data.canEdit) {
          wx.showToast({ title: '该记账记录不允许编辑', icon: 'success' });
          this.setData({
            submitDisabled: true,
            submitBtnText: '该状态下禁止操作'
          });
          // this.backAndRefresh();
          // return;
        }
        
        if (data.categoryCode) {
          // 查找对应的分类
          const categoryList = this.data.type === 'expense' ? 
            this.data.expenseCategoryList : this.data.incomeCategoryList;
          const categoryIndex = categoryList.findIndex(item => 
            item.name === data.categoryCode || item.name.includes(data.categoryCode)
          );
          
          if (categoryIndex >= 0) {
            const category = categoryList[categoryIndex];
            this.setData({
              categoryName: category.name,
              categoryIcon: category.icon,
              categoryIndex: categoryIndex // 添加分类索引设置
            });
          }
        }

        // 支付方式处理
        if (data.paymentMethod) {
          // 查找对应的支付方式
          const paymentIndex = this.data.paymentList.findIndex(item => 
            item.name === data.paymentMethod || item.name.includes(data.paymentMethod)
          );
          
          if (paymentIndex >= 0) {
            // 能找到存在的支付方式
            this.setData({
              paymentIndex: paymentIndex
            });
          } else {
            // 找不到就在支付方式后面添加新的
            this.data.paymentList.push({name: data.paymentMethod, defaultFlag: 'no'});
            this.setData({
              // 显示最后一个
              paymentIndex: this.data.paymentList.length -1
            });
          }
        }
        
        if (data.financeDate) {
          this.setData({ financeDate: data.financeDate });
        }
        
        if (data.desc) {
          this.setData({ remark: data.desc });
        }
        
        // 填充明细
        if (data.items && Array.isArray(data.items)) {
          const details = data.items.map(item => ({
            id: Date.now() + Math.random(),
            name: item.name || '',
            unitPrice: item.unit || '',
            quantity: item.quantity || 1,
            amount: item.amount || '',
            timeStr: item.timeStr || ''
          }));
          this.setData({ details });
        }
      } catch (e) {
        console.error('填充表单失败', e);
        wx.showToast({ title:  (e && e.data && e.data.msg) || '解析结果格式错误', icon: 'none' });
      }
    },

    // 账单截图识别
    onScreenshotRecognition() {
      this.handleImageRecognition(
        finance.screenshotRecognition,
        '截图识别中...',
        '识别成功',
        '识别失败'
      );
    },

    // 小票识别
    onUploadReceipt() {
      this.handleImageRecognition(
        finance.consumeTipRecognition,
        '识别中...',
        '识别成功',
        '识别失败'
      );
    },
    onDeleteRecord() {
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        confirmColor: '#d32f2f',
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '删除中...' });
            finance.deleteFinanceRecord(this.data.recordId).then(() => {
              wx.hideLoading();
              wx.showToast({ title: '删除成功', icon: 'success' });
              this.backAndRefresh();
            }).catch((e) => {
              wx.hideLoading();
              wx.showToast({ title:  (e && e.data && e.data.msg) || '删除失败', icon: 'none' });
            });
          }
        }
      });
    },
    
    // 拆分记录
    onSplitRecord() {
      wx.showModal({
        title: '确认拆分',
        content: '该记录将根据每个明细拆分成多个记录，请谨慎提交。',
        confirmColor: '#1976d2',
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '拆分中...' });
            finance.splitRecord(this.data.recordId).then(() => {
              wx.hideLoading();
              wx.showToast({ title: '拆分成功', icon: 'success' });
              // 关闭当前页面，跳转到拆分结果页面
              wx.redirectTo({
                url: `/pages/finance/split-result/split-result?splitId=${this.data.recordId}`
              });
            
            }).catch((e) => {
              wx.hideLoading();
              wx.showToast({ title: (e && e.data && e.data.msg) || '拆分失败', icon: 'none' });
            });
          }
        }
      });
    },
    /**
     * 返回上一页刷新
     */
    backAndRefresh() {
      // 返回上一个页面并刷新
      const pages = getCurrentPages();
      if (pages.length > 1) {
        const prevPage = pages[pages.length - 2];
        if (prevPage && typeof prevPage.loadRecords === 'function') {
          prevPage.loadRecords(true);
        }
      }
      wx.navigateBack();
    },
    /**
     * 金额汇总
     */
    updateAmountFromDetails() {
      const details = this.data.details || [];
      const total = details.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0);
      this.setData({ amount: total ? total.toFixed(2) : '' });
    },
    /**
     * 选择支付方式
     * @param {*} e 
     */
    onPaymentChange(e) {
      this.setData({ paymentIndex: e.detail.value });
    },
    clickShowAccountSelector() {
      this.setData({ showAccountSelector: true });
    },
    onSelectAccount(e) {
      const idx = e.detail.index;
      console.log('账户选择:', idx, '账户列表:', this.data.accountList);
      
      // 验证索引是否有效
      if (idx >= 0 && idx < this.data.accountList.length) {
        // 更新账户索引
        this.setData({ accountIndex: idx });
        // 设置全局账户索引
        if (app && typeof app.setAccountIdxGlobal === 'function') {
          app.setAccountIdxGlobal(idx);
        }
        console.log('账户切换成功，新账户:', this.data.accountList[idx].name);
      } else {
        console.error('无效的账户索引:', idx);
        wx.showToast({ title: '账户选择失败', icon: 'none' });
      }
    },
    
    // 图片点击查看
    onImageTap(e) {
      const imageSrc = e.currentTarget.dataset.src;
      if (imageSrc) {
        wx.previewImage({
          current: imageSrc,
          urls: [imageSrc]
        });
      }
    },
    
    // 初始化/获取全局音频实例
    getAudioCtx() {
      if (!this.innerAudioContext) {
        console.log('创建新的音频实例');
        const ctx = wx.createInnerAudioContext();
        
        // 基本配置
        ctx.obeyMuteSwitch = false; // 不遵循系统静音开关
        ctx.autoplay = false; // 不自动播放
        
        // 事件绑定 - 只使用微信小程序支持的事件
        ctx.onCanplay(() => {
          console.log('音频可以播放');
          // 在音频可以播放时获取时长信息
          this.updateAudioDuration();
        });
        
        ctx.onTimeUpdate(() => {
          // 更新播放进度
          this.updateAudioProgress();
        });
        
        ctx.onPlay(() => {
          console.log('音频开始播放');
          this.setData({ isAudioPlaying: true });
        });
        
        ctx.onPause(() => {
          console.log('音频暂停');
          this.setData({ 
            isAudioPlaying: false,
            // 暂停时保持当前进度，不重置
          });
        });
        
        ctx.onStop(() => {
          console.log('音频停止');
          this.setData({ 
            isAudioPlaying: false,
            audioCurrentTime: 0,
            audioProgress: 0
          });
        });
        
        ctx.onEnded(() => {
          console.log('音频播放结束');
          this.setData({ 
            isAudioPlaying: false,
            audioCurrentTime: 0,
            audioProgress: 0
          });
        });
        
        ctx.onError((err) => {
          console.error('音频播放错误:', err);
          this.setData({ 
            isAudioPlaying: false,
            audioCurrentTime: 0,
            audioProgress: 0
          });
          wx.showToast({ 
            title: '音频播放失败: ' + (err.errMsg || '未知错误'), 
            icon: 'none',
            duration: 3000
          });
        });
        

        
        ctx.onWaiting(() => {
          console.log('音频加载中...');
        });
        
        this.innerAudioContext = ctx;
        console.log('音频实例创建完成');
      }
      return this.innerAudioContext;
    },
    
    // 音频播放/暂停切换
    onAudioPlay(e) {
      console.log('音频播放触发:', e);
      
      // 获取音频URL
      let url = '';
      if (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.src) {
        url = e.currentTarget.dataset.src;
      } else {
        url = this.data.resourceUrl;
      }
      
      console.log('音频URL:', url);
      console.log('当前媒体类型:', this.data.mediaType);
      console.log('当前播放状态:', this.data.isAudioPlaying);
      console.log('音频实例src:', this.innerAudioContext ? this.innerAudioContext.src : 'null');
      
      if (!url) {
        wx.showToast({ title: '无效的音频地址', icon: 'none' });
        return;
      }
      
      // 验证URL格式
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        wx.showToast({ title: '音频地址格式错误', icon: 'none' });
        return;
      }
      
      const audio = this.getAudioCtx();
      console.log('音频实例:', audio);
      console.log('音频实例src:', audio.src);
      console.log('当前播放状态:', this.data.isAudioPlaying);
      
      try {
        // 如果当前已设置相同src并在播放，则切换为暂停
        if (audio.src === url && this.data.isAudioPlaying) {
          console.log('暂停音频播放');
          audio.pause();
          // 暂停后立即更新UI状态
          this.setData({ isAudioPlaying: false });
          return;
        }
        
        // 如果当前已设置相同src但未在播放，则继续播放
        if (audio.src === url && !this.data.isAudioPlaying) {
          console.log('继续播放音频');
          audio.play();
          // 立即更新播放状态
          this.setData({ isAudioPlaying: true });
          return;
        }
        
        // 停止当前播放
        if (this.data.isAudioPlaying) {
          audio.stop();
          this.setData({ isAudioPlaying: false });
        }
        
        // 设置新的音频源
        console.log('设置音频源:', url);
        audio.src = url;
        
        // 播放音频
        console.log('开始播放音频');
        audio.play();
        
        // 立即更新播放状态
        this.setData({ isAudioPlaying: true });
        
        // 显示加载提示
        wx.showToast({ title: '正在加载音频...', icon: 'loading', duration: 1000 });
        
        // 延时检查音频时长（微信小程序可能需要播放一段时间后才能获取到时长）
        setTimeout(() => {
          this.updateAudioDuration();
        }, 500);
        
      } catch (err) {
        console.error('音频播放失败:', err);
        wx.showToast({ title: '播放失败: ' + (err.message || err), icon: 'none' });
        // 播放失败时重置状态
        this.setData({ isAudioPlaying: false });
      }
    },
    
    // 暂停音频播放
    onAudioPause() {
      console.log('手动暂停音频');
      if (this.innerAudioContext) {
        this.innerAudioContext.pause();
        // 暂停时保持当前进度，不重置
      }
    },
    
    // 停止音频播放
    onAudioStop() {
      console.log('停止音频播放');
      if (this.innerAudioContext) {
        this.innerAudioContext.stop();
        // 手动重置状态
        this.setData({ 
          isAudioPlaying: false,
          audioCurrentTime: 0,
          audioProgress: 0
        });
      }
    },
    
    // 格式化时间显示
    formatTime(seconds) {
      if (!seconds || seconds < 0) return '00:00';
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    
    // 更新音频时长信息
    updateAudioDuration() {
      if (this.innerAudioContext && this.innerAudioContext.duration) {
        const duration = Math.floor(this.innerAudioContext.duration);
        if (duration > 0) {
          this.setData({ 
            audioDuration: duration,
            audioCurrentTime: 0,
            audioProgress: 0
          });
          console.log('音频总长度:', duration, '秒');
        }
      }
    },
    
    // 更新音频播放进度
    updateAudioProgress() {
      if (this.innerAudioContext && this.innerAudioContext.currentTime && this.innerAudioContext.duration) {
        const currentTime = Math.floor(this.innerAudioContext.currentTime);
        const duration = Math.floor(this.innerAudioContext.duration);
        const progress = Math.floor((currentTime / duration) * 100);
        
        this.setData({ 
          audioCurrentTime: currentTime,
          audioProgress: progress
        });
      }
    },
    
    // 页面隐藏/卸载时释放音频资源
    onHide() {
      console.log('页面隐藏，停止音频');
      if (this.innerAudioContext) {
        try { 
          this.innerAudioContext.stop(); 
          this.setData({ isAudioPlaying: false });
        } catch (e) {
          console.error('停止音频失败:', e);
        }
      }
    },
    
    onUnload() {
      console.log('页面卸载，销毁音频实例');
      if (this.innerAudioContext) {
        try { 
          this.innerAudioContext.destroy(); 
          this.innerAudioContext = null;
          this.setData({ isAudioPlaying: false });
        } catch (e) {
          console.error('销毁音频实例失败:', e);
        }
      }
    },
    
    // 测试音频播放（调试用）
    testAudioPlay() {
      console.log('测试音频播放');
      const testUrl = 'https://pinxuango.cn/minio/pinxuan-video/20250825/8503ee9176454343ac624309b4258870.mp3';
      console.log('测试URL:', testUrl);
      
      // 直接测试URL是否可访问
      wx.request({
        url: testUrl,
        method: 'HEAD',
        success: (res) => {
          console.log('音频资源检查成功:', res);
          console.log('Content-Type:', res.header['Content-Type']);
          console.log('Content-Length:', res.header['Content-Length']);
          
          // 尝试播放
          this.testPlayAudio(testUrl);
        },
        fail: (err) => {
          console.error('音频资源检查失败:', err);
          wx.showToast({ 
            title: '音频资源不可访问: ' + (err.errMsg || '网络错误'), 
            icon: 'none',
            duration: 3000
          });
        }
      });
    },
    
    // 测试播放音频
    testPlayAudio(url) {
      try {
        const audio = this.getAudioCtx();
        console.log('测试播放音频:', url);
        
        audio.src = url;
        audio.play();
        
        // 立即更新状态
        this.setData({ isAudioPlaying: true });
        
        wx.showToast({ title: '测试播放中...', icon: 'loading', duration: 2000 });
        
      } catch (err) {
        console.error('测试播放失败:', err);
        wx.showToast({ title: '测试播放失败: ' + err.message, icon: 'none' });
        this.setData({ isAudioPlaying: false });
      }
    },
    
    // 手动切换播放状态（调试用）
    toggleAudioState() {
      const newState = !this.data.isAudioPlaying;
      console.log('手动切换音频状态:', this.data.isAudioPlaying, '->', newState);
      this.setData({ isAudioPlaying: newState });
    },
  });